<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="stylesheet" href="static/login.css">
<title>登录</title>
<script>
    async function handleLogin(event) {
        event.preventDefault(); // 阻止表单默认提交行为

        const formData = new FormData(event.target);
        const username = formData.get('username');
        const password = formData.get('password');

        try {
            const response = await fetch('/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: `username=${encodeURIComponent(username)}&password=${encodeURIComponent(password)}`
            });

            if (!response.ok) {
                const error = await response.json();
                alert(error.detail); // 显示后端返回的错误消息
            } else {
                // 登录成功，重定向到另一个页面（这里假设是 /dashboard）
                window.location.href = '/dashboard';
            }
        } catch (error) {
            console.error('Error:', error);
            alert('An unexpected error occurred. Please try again later.');
        }
    }
</script>
</head>
<body>
<form onsubmit="handleLogin(event)">
    <div id="login-box">
        <h1>登录</h1>
        <div class="form">
            <div class="item">
                <i class="fa fa-user-circle-o" aria-hidden="true"></i>
                <input type="text" name="username" placeholder="Username" id="username1" maxlength="20">
            </div>
            <div class="item">
                <i class="fa fa-key" aria-hidden="true"></i>
                <input type="password" name="password" placeholder="Password" id="password1" maxlength="20">
            </div>
        </div>
        <button type="submit">Login</button>
    </div>
</form>
</body>
</html>